package com.wxy.ej.flow.modules.act.service.beanService;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rt.easyjava.common.base.PageDto;
import com.rt.easyjava.common.base.Result;
import com.rt.easyjava.common.config.dozer.MyMapper;
import com.rt.easyjava.common.utils.others.DateUtils;
import com.rt.easyjava.common.utils.others.JsonUtils;
import com.wxy.ej.flow.modules.act.bean.FormData;
import com.wxy.ej.flow.modules.act.dto.FormDataDto;
import com.wxy.ej.flow.modules.act.dto.ProcessDefinitionDto;
import com.wxy.ej.flow.modules.act.dto.TaskDto;
import com.wxy.ej.flow.modules.act.dto.TaskQueryDto;
import org.activiti.engine.*;
import org.activiti.engine.form.FormProperty;
import org.activiti.engine.form.StartFormData;
import org.activiti.engine.form.TaskFormData;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceQuery;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class ActivitiUtilsService {
    @Resource private MyMapper mapper;
    @Resource private RuntimeService runtimeService;
    @Resource private RepositoryService repositoryService;
    @Resource private TaskService taskService;
    @Resource private FormService formService;
    @Resource private HistoryService historyService;
    @Resource private IdentityService identityService;
    @Resource private FormDataService formDataService;
    @Resource private ActImageService actImageService;

    /**
     * 我发起的流程，正在执行中的流程
     * @param userId
     * @return
     */
    public Result listMyStartProcInstRunningByUserId(TaskQueryDto taskQueryDto, String userId) {
        ProcessInstanceQuery processInstanceQuery = runtimeService.createProcessInstanceQuery().
                startedBy(userId);

        List<ProcessInstance> piList = processInstanceQuery.orderByProcessInstanceId().desc()
                .listPage((taskQueryDto.getPage()-1)*taskQueryDto.getLimit(), taskQueryDto.getLimit());
        int total =  (int)processInstanceQuery.count();

        // 正在运行的流程
        List<Map<String, Object>> list = new ArrayList<>();
        for (ProcessInstance pi : piList) {
            Map<String, Object> map = new HashMap<>();
            map.put("procInstId", pi.getId());
            map.put("procInstName", pi.getName());
            map.put("procInstStartUserId", pi.getStartUserId());
            map.put("procInstStartTime", DateUtils.formatDate(pi.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
            map.put("isProcessEnd", isProcessEnd(pi.getId()));
            map.put("processStatus", isProcessEnd(pi.getId())?"已完成111":"执行中" );
            list.add(map);
        }

        return Result.builder(list).setTotal(total).success();
    }

    /**
     * 我发起的流程，已完成了的历史流程
     * @param userId
     * @return
     */
    public Result listMyStartProcInstHisByUserId(TaskQueryDto taskQueryDto, String userId) {
        // 正在运行的流程
        List<Map<String, Object>> list = new ArrayList<>();

        // 已结束的历史流程
        HistoricProcessInstanceQuery historicProcessInstanceQuery = historyService.createHistoricProcessInstanceQuery()
                .startedBy(userId)
                .finished();

        List<HistoricProcessInstance> hisPiList = historicProcessInstanceQuery
                .orderByProcessInstanceStartTime()
                .desc()
                .listPage((taskQueryDto.getPage()-1)*taskQueryDto.getLimit(), taskQueryDto.getLimit());
        int total = (int)historicProcessInstanceQuery.count();

        for (HistoricProcessInstance pi : hisPiList) {
            Map<String, Object> map = new HashMap<>();
            map.put("procInstId", pi.getId());
            map.put("procInstName", pi.getName());
            map.put("procInstStartUserId", pi.getStartUserId());
            map.put("procInstStartTime", DateUtils.formatDate(pi.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
            map.put("isProcessEnd", isProcessEnd(pi.getId()));
            map.put("processStatus", isProcessEnd(pi.getId())?"已结束":"未结束222" );
            list.add(map);
        }

        return Result.builder(list).setTotal(total).success();
    }



    public boolean isProcessEnd(String processInstanceId) {
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        if (processInstance != null) {
            return processInstance.isEnded();
        }
        return true;
    }





}
